import requests
from common.internal_random import generate_random_uint32
from common.config import cfg
import TLSSigAPIv2
SDKAPPID = cfg['im_sdk_appid']
SECRET_KEY = cfg['im_sdk_key']

class TencentIM:
    def __init__(self, sdk_app_id = SDKAPPID, secret_key = SECRET_KEY):
        """
        初始化 TencentIM 类。

        :param sdk_app_id: 腾讯云 IM 应用的 SDKAppID
        :param secret_key: 腾讯云 IM 应用的密钥
        """
        self.sdk_app_id = sdk_app_id
        self.secret_key = secret_key
        self.api_base_url = "https://console.tim.qq.com/"
        self.sig_api = TLSSigAPIv2.TLSSigAPIv2(sdk_app_id, secret_key)
    
    async def register_user(self, user_id: str, nickname: str = "", face_url: str = ""):
        """
        注册用户
        """
        url = self.api_base_url + "v4/im_open_login_svc/account_import"
        params = {
            "sdkappid": self.sdk_app_id,
            "identifier": "administrator",  # 使用管理员账号作为请求者
            "usersig":self.sig_api.gen_sig('administrator'),
            "random": generate_random_uint32(),
            "contenttype": "json"
        }
        data = {
            "UserID": user_id,
            "Nick": nickname,
        }
        
        try:
            response = requests.post(url, params=params, json=data)
            response.raise_for_status()
            if response.json().get("ActionStatus") == 'OK':
                return True,None
            else:
                return False,response.json().get("ErrorInfo")
        except requests.exceptions.RequestException as e:
            return False,str(e)
     
    async def delete_user(self, user_ids):
        """
        删除用户
        """

        url = self.api_base_url + "v4/im_open_login_svc/account_delete"
        params = {
            "sdkappid": self.sdk_app_id,
            "identifier": "administrator",  # 使用管理员账号作为请求者
            "usersig":self.sig_api.gen_sig('administrator'),
            "random": generate_random_uint32(),
            "contenttype": "json"
        }
        data = {
            "DeleteItem": [{"UserID": user_id} for user_id in user_ids]
            }
        
        try:
            response = requests.post(url, params=params, json=data)
            response.raise_for_status()
            print(response.json())
            if response.json().get("ActionStatus") == 'OK':
                return True,None
            else:
                return False,response.json().get("ErrorInfo")
        except requests.exceptions.RequestException as e:
            return False,str(e)
 
    async def send_msg(self,from_user, to_user,msg):
        """
        发送消息"
        """
        url = self.api_base_url + "v4/openim/sendmsg"
        params = {
            "sdkappid": self.sdk_app_id,
            "identifier": "administrator",  # 使用管理员账号作为请求者
            "usersig":self.sig_api.gen_sig('administrator'),
            "random": generate_random_uint32(),
            "contenttype": "json" 
        }
        data = {
            "From_Account": from_user,
            "To_Account": to_user,
            "MsgBody": [
                {
                    "MsgType": "TIMTextElem",
                    "MsgContent": {
                        "Text": msg
                    }
                }
            ],
            "MsgRandom": generate_random_uint32(),
            "SyncOtherMachine": 1
        }
        try:    
            response = requests.post(url, params=params, json=data)
            response.raise_for_status()
            if response.json().get("ActionStatus") == 'OK':
                print(response.json())
                return True,None
            else:
                return False,response.json().get("ErrorInfo")
        except requests.exceptions.RequestException as e:
            return False,str(e)

    async def create_group(self, group_name: str, introduction: str = "", notification: str = "", member_list: list = None, owner_id: str = None):
        """
        创建群组
        """
        url = self.api_base_url + "v4/group_open_http_svc/create_group"
        params = {
            "sdkappid": self.sdk_app_id,
            "identifier": "administrator",
            "usersig": self.sig_api.gen_sig('administrator'),
            "random": generate_random_uint32(),
            "contenttype": "json"
        }
        
        data = {
            "Type": "Public",
            "Name": group_name,
            "Introduction": introduction,
            "Notification": notification,
            "MaxMemberCount": 200,
            "ApplyJoinOption": "FreeAccess"
        }

        # 设置群主
        if owner_id:
            data["Owner_Account"] = str(owner_id)
        print(data)
        # 如果有成员列表，添加到请求数据中
        if member_list:
            data["MemberList"] = [{"Member_Account": member} for member in member_list]

        try:
            response = requests.post(url, params=params, json=data)
            response.raise_for_status()
            result = response.json()
            
            if result.get("ActionStatus") == "OK":
                return True, result.get("GroupId")
            else:
                return False, result.get("ErrorInfo")
        except requests.exceptions.RequestException as e:
            return False, str(e)
    
    async def delete_group(self, group_id: str):
        """
        删除群组
        """
        url = self.api_base_url + "v4/group_open_http_svc/destroy_group"
        params = {
            "sdkappid": self.sdk_app_id,
            "identifier": "administrator",
            "usersig": self.sig_api.gen_sig('administrator'),
            "random": generate_random_uint32(),
            "contenttype": "json"
        }
        
        data = {
            "GroupId": group_id
        }

        try:
            response = requests.post(url, params=params, json=data)
            response.raise_for_status()
            result = response.json()
            
            if result.get("ActionStatus") == "OK":
                return True, None
            else:
                return False, result.get("ErrorInfo")
        except requests.exceptions.RequestException as e:
            return False, str(e)

# async def test_group_operations():
# im = TencentIM()

# # 创建群组
# members = ["1", "2", "3"]  # 替换为实际的用户ID
# success, group_id = await im.create_group(
#     group_name="测试活动群",
#     introduction="这是一个测试活动群",
#     notification="欢迎加入测试群！",
#     member_list=members
# )

# if success:
#     print(f"群组创建成功，群ID：{group_id}")
    
#     # 等待一段时间后删除群组
#     await asyncio.sleep(5)  # 等待5秒
    
#     # 删除刚创建的群组
#     delete_success, error = await im.delete_group(group_id)
#     if delete_success:
#         print("群组删除成功")
#     else:
#         print(f"群组删除失败：{error}")
# else:
#     print(f"群组创建失败：{group_id}")  # 创建失败时 group_id 包含错误信息

import asyncio
if __name__ == "__main__":
    im = TencentIM()

    # 测试用户注册
    # test_user_id = "test_user_001"
    # register_result = im.register_user(
    #     user_id=test_user_id,
    # )
    # print("用户注册结果:", register_result)

    # 测试用户删除
    # user_ids_to_delete = [test_user_id]
    # delete_result = im.delete_user(user_ids_to_delete)
    # print("用户删除结果:", delete_result)

    # 测试发送消息

    # asyncio.run(main())
    # asyncio.run(test_group_operations())